<template>
	<el-dialog v-model="dialog" :title="state.form.id ? '修改规格' : '添加规格'" width="40%" :before-close="handleClose">
		<el-form ref="formRef" :model="state.form" :rules="state.rules">
			<el-form-item label="规格名" prop="name">
				<el-input v-model="state.form.name"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">关 闭</el-button>
				<el-button type="primary" :loading="loading" @click="submitForm(formRef)">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { addObj, editObj, getById } from '/@/api/product/goodsspecs';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
const emit = defineEmits(['initPage']);
const state = reactive({
	form: { id: undefined, name: '' },
	rules: {
		name: [
			{
				required: true,
				message: '请输入规格名',
				trigger: 'change',
			},
		],
	},
});
const dialog = ref(false);
const loading = ref(false);
const formRef = ref();

const initForm = (row: any) => {
	dialog.value = true;
	if (row && row.id) {
		getDetail(row.id);
	}
};
const getDetail = (id: string) => {
	loading.value = true;
	// 修改
	getById(id)
		.then((response) => {
			loading.value = false;
			state.form = response.data.data;
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 关闭事件
 */
const handleClose = () => {
	resetForm(formRef.value);
};
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.form.id = undefined;
	loading.value = false;
	dialog.value = false;
	formEl.resetFields();
};
/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			loading.value = true;
			if (state.form.id) {
				//修改
				edit();
			} else {
				//新增
				add();
			}
		}
	});
};
/**
 * 新增
 */
const add = () => {
	addObj(state.form)
		.then((response) => {
			resetForm(formRef.value);
			ElMessage.success('新增成功');
			emit('initPage');
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 修改
 */
const edit = () => {
	editObj(state.form)
		.then((response) => {
			resetForm(formRef.value);
			ElMessage.success('修改成功');
			emit('initPage');
		})
		.catch(() => {
			loading.value = false;
		});
};
defineExpose({
	initForm,
});
</script>
<style lang="scss"></style>
